package com.example.myapplication.peripheral;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCallback;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.bluetooth.BluetoothManager;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.le.BluetoothLeScanner;
import android.bluetooth.le.ScanCallback;
import android.bluetooth.le.ScanFilter;
import android.bluetooth.le.ScanResult;
import android.bluetooth.le.ScanSettings;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.util.Log;

import androidx.annotation.NonNull;

import com.example.myapplication.DataSet.breatheData;
import com.example.myapplication.DataSet.ppgData;
import com.example.myapplication.MainActivity;
import com.example.myapplication.algorithm.MovingAverageSmoother;
import com.example.myapplication.algorithm.filter;
import com.example.myapplication.ui.home.HomeInterfaceInstant;
import com.github.mikephil.charting.data.Entry;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicBoolean;

public class UserBluetooth {
    private static final String TAG = "UserBluetooth";
    private static final UUID UUID_SERVICE = UUID.fromString("8b3bd5f2-d9f6-4627-8d4a-95528b20f5ed");
    private static final UUID UUID_CHARACTERISTIC_NOTIFY1 = UUID.fromString("c48d0417-de7a-41ef-b34c-1c1f0202a53f");
    private static final UUID UUID_CHARACTERISTIC_NOTIFY2 = UUID.fromString("c48d0418-de7a-41ef-b34c-1c1f0202a53f");
    private static final UUID UUID_CHARACTERISTIC_NOTIFY3 = UUID.fromString("c48d0419-de7a-41ef-b34c-1c1f0202a53f");
    private static final UUID UUID_CHARACTERISTIC_NOTIFY4 = UUID.fromString("c48d0420-de7a-41ef-b34c-1c1f0202a53f");
    private static final UUID UUID_CHARACTERISTIC_WRITE = UUID.fromString("33bd79a8-fc9a-4201-b682-2b029130b90e");
    private static final UUID CLIENT_CHARACTERISTIC_CONFIG_UUID = UUID.fromString("00002902-0000-1000-8000-00805f9b34fb");
    private BluetoothManager bluetoothManager;
    private BluetoothAdapter bluetoothAdapter;
    private BluetoothLeScanner bluetoothLeScanner;
    public BluetoothGatt bluetoothGatt;
    private final static int REQUEST_ENABLE_BT = 1;
    private final static int DEFAULT_MTU = 23;
    private final static int REQUEST_MTU = 247; // Maximum MTU size for BLE
    private static final String targetDeviceName = "UART_BLE"; // 设置目标设备名称
    private BluetoothGattCharacteristic mCharacteristic_notify1;
    private BluetoothGattCharacteristic mCharacteristic_notify2;
    private BluetoothGattCharacteristic mCharacteristic_notify3;
    private BluetoothGattCharacteristic mCharacteristic_notify4;
    public BluetoothGattCharacteristic mCharacteristic_write;
    private static UserBluetooth INSTANCE;
    private Context context;
    private final AtomicBoolean isInited = new AtomicBoolean(false);
    private final AtomicBoolean isConnect = new AtomicBoolean(false);
    public boolean isInit() {
        return isInited.get();
    }
    public boolean isConnect(){
        return isConnect.get();
    }
    public CSVDataLogger csvDataLogger_ecg;
    public CSVDataLogger csvDataLogger_acc;
    public CSVDataLogger csvDataLogger_breathe;
    public CSVDataLogger csvDataLogger_breathe_filtered;
    public CSVDataLogger csvDataLogger_ppg;
    public CSVDataLogger csvDataLogger_ppg_filtered;

    private List<BluetoothDevice> scannedDevices = new ArrayList<>();
    private DeviceListDialog deviceListDialog;
    public synchronized static UserBluetooth getInstance() {
        if (INSTANCE == null) {
            INSTANCE = new UserBluetooth();
        }
        return INSTANCE;
    }
    @SuppressLint("MissingPermission")
    public void init(Activity activity) {
        Log.i(TAG, "init bluetooth 1");
        bluetoothManager = (BluetoothManager) activity.getSystemService(Context.BLUETOOTH_SERVICE);
        bluetoothAdapter = bluetoothManager.getAdapter();
        context = activity;
        if (bluetoothAdapter == null || !bluetoothAdapter.isEnabled()) {
            Log.i(TAG, "init bluetooth");
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            activity.startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
        }
        //startScan();
    }

    @SuppressLint("MissingPermission")
    public void close() {
        if (bluetoothGatt != null) {
            bluetoothGatt.disconnect();
            bluetoothGatt.close();
            bluetoothGatt = null;
        }
    }
    public void showDeviceListDialog() {
        scannedDevices.clear();
        deviceListDialog = new DeviceListDialog(context, scannedDevices, device -> {
            stopScan();
            connectToDevice(device);
        });
        deviceListDialog.show();
        // Start scanning for devices to show in list
        startScan();
    }
    @SuppressLint("MissingPermission")
    public void startScan() {
        Log.i(TAG, "startScan");
        bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();
        ScanSettings scanSettings = new ScanSettings.Builder()
                .setScanMode(ScanSettings.SCAN_MODE_BALANCED)
                .build();
        // 设置扫描过滤器（可选）
        List<ScanFilter> scanFilters = new ArrayList<>();

        // 根据情况可按条件进行蓝牙扫描
        if (targetDeviceName != null) {
            ScanFilter nameFilter = new ScanFilter.Builder()
                    .setDeviceName(targetDeviceName)
                    .build();
            scanFilters.add(nameFilter);
        }
        bluetoothLeScanner.startScan(scanFilters, scanSettings, scanCallback);
    }

    @SuppressLint("MissingPermission")
    private void stopScan() {
        if (bluetoothLeScanner != null) {
            bluetoothLeScanner.stopScan(scanCallback);
        }
    }
    private boolean containsDevice(List<BluetoothDevice> devices, BluetoothDevice newDevice) {
        for (BluetoothDevice device : devices) {
            if (device.getAddress().equals(newDevice.getAddress())) {
                return true;
            }
        }
        return false;
    }
    @SuppressLint("MissingPermission")
    private final ScanCallback scanCallback = new ScanCallback() {
        @Override
        public void onScanResult(int callbackType, ScanResult result) {
            super.onScanResult(callbackType, result);
            BluetoothDevice device = result.getDevice();
            String deviceName = device.getName();
            String deviceAddress = device.getAddress();
            Log.d(TAG, "Found device: " + deviceName + " - " + deviceAddress);

            // 过滤设备：根据名称和MAC地址
//            if (deviceName != null && deviceName.contains(targetDeviceName)) {
//                Log.d(TAG, "Found target device by name: " + deviceName);
//                connectToDevice(device);
//            }

            if (!containsDevice(scannedDevices, device)) {
                scannedDevices.add(device);
                if (deviceListDialog != null && deviceListDialog.isShowing()) {
                    ((Activity)context).runOnUiThread(() -> {
                        deviceListDialog.updateList(scannedDevices);
                    });
                }
            }
        }
        @Override
        public void onScanFailed(int errorCode) {
            super.onScanFailed(errorCode);
            Log.e(TAG, "Scan failed with error code: " + errorCode);
        }
    };

    @SuppressLint("MissingPermission")
    private void connectToDevice(BluetoothDevice device) {
        // 停止扫描
        stopScan();
        // 连接设备
        bluetoothGatt = device.connectGatt(context, true, gattCallback);
    }

    private final BluetoothGattCallback gattCallback = new BluetoothGattCallback() {
        @SuppressLint("MissingPermission")
        @Override
        public void onConnectionStateChange(BluetoothGatt gatt, int status, int newState) {
            super.onConnectionStateChange(gatt, status, newState);
            if (newState == BluetoothProfile.STATE_CONNECTED) {
                isConnect.compareAndSet(false,true);
                Log.d(TAG, "Connected to GATT server.");
                //Toast.makeText(context, "蓝牙连接成功", Toast.LENGTH_SHORT).show();
                // 发现服务
                gatt.discoverServices();
            } else if (newState == BluetoothProfile.STATE_DISCONNECTED) {
                isConnect.compareAndSet(true,false);
                Log.d(TAG, "Disconnected from GATT server.");
            }
        }

        @SuppressLint("MissingPermission")
        @Override
        public void onServicesDiscovered(BluetoothGatt gatt, int status) {
            super.onServicesDiscovered(gatt, status);
            if (status == BluetoothGatt.GATT_SUCCESS) {
                Log.d(TAG, "Services discovered.");
                List<BluetoothGattService> services = gatt.getServices();
                for (BluetoothGattService service : services) {
                    Log.d(TAG, "Service UUID: " + service.getUuid().toString());
                }
                // Request MTU update
                gatt.requestMtu(REQUEST_MTU);

                // Enable notifications for a specific characteristic
                BluetoothGattService service = gatt.getService(UUID_SERVICE);
                if (service != null) {
                    try {
                        mCharacteristic_notify1 = service.getCharacteristic(UUID_CHARACTERISTIC_NOTIFY1);
                        Thread.sleep(500);
                        mCharacteristic_notify2 = service.getCharacteristic(UUID_CHARACTERISTIC_NOTIFY2);
                        Thread.sleep(500);
                        mCharacteristic_notify3 = service.getCharacteristic(UUID_CHARACTERISTIC_NOTIFY3);
                        Thread.sleep(500);
                        mCharacteristic_notify4 = service.getCharacteristic(UUID_CHARACTERISTIC_NOTIFY4);
                        Thread.sleep(500);
                        mCharacteristic_write = service.getCharacteristic(UUID_CHARACTERISTIC_WRITE);
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            try {
                                if (mCharacteristic_notify1 != null) {
                                    enableNotifications(gatt, mCharacteristic_notify1);
                                }
                                Thread.sleep(500);
                                if (mCharacteristic_notify2 != null) {
                                    enableNotifications(gatt, mCharacteristic_notify2);
                                }
                                Thread.sleep(500);
                                if (mCharacteristic_notify3 != null) {
                                    enableNotifications(gatt, mCharacteristic_notify3);
                                }
                                Thread.sleep(500);
                                if (mCharacteristic_notify4 != null) {
                                    enableNotifications(gatt, mCharacteristic_notify4);
                                }
                                Thread.sleep(500);
                            } catch (InterruptedException e) {
                                throw new RuntimeException(e);
                            }
                        }
                    }).start();
                }
            }
        }
        @Override
        public void onCharacteristicChanged(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
            super.onCharacteristicChanged(gatt, characteristic);
            if(HomeInterfaceInstant.getInstance().get_flag() == true) {
                return;
            }
            byte[] data = characteristic.getValue();
            //Log.d(TAG, "len = " + data.length);
            //Log.d(TAG, "data = " + DataUtils.bytesToHexStr(data));
            if(characteristic.getUuid().toString().equals(UUID_CHARACTERISTIC_NOTIFY1.toString())) {
                /* 发送cECG */
                Message msg = new Message();
                msg.what = HANDLE_MESSAGE_ECG;
                msg.obj = data;
                mHandler.sendMessage(msg);
            }
            else if(characteristic.getUuid().toString().equals(UUID_CHARACTERISTIC_NOTIFY2.toString())){
                String str = new String(data);
                if(str.contains("hr")) {
                    Message msg = new Message();
                    msg.obj = str;
                    msg.what = HANDLE_MESSAGE_HR;
                    mHandler.sendMessage(msg);
                } else if (str.contains("SO2")) {
                    Message msg = new Message();
                    msg.obj = str;
                    msg.what = HANDLE_MESSAGE_SO2;
                    mHandler.sendMessage(msg);
                } else if (str.contains("Battery")) {
                    Message msg = new Message();
                    msg.obj = str;
                    msg.what = HANDLE_MESSAGE_BATTERY;
                    mHandler.sendMessage(msg);
                }
                else {
                    // 发送ACC
                    Message msg = new Message();
                    msg.obj = str;
                    msg.what = HANDLE_MESSAGE_ACC;
                    mHandler.sendMessage(msg);
                }
            }
            else if(characteristic.getUuid().toString().equals(UUID_CHARACTERISTIC_NOTIFY3.toString())) {
                // 发送breathe
                Message msg = new Message();
                msg.what = HANDLE_MESSAGE_BREATHE;
                msg.obj = data;
                mHandler.sendMessage(msg);
            }
            else if (characteristic.getUuid().toString().equals(UUID_CHARACTERISTIC_NOTIFY4.toString())){
                // 发送PPG
                Message msg = new Message();
                msg.what = HANDLE_MESSAGE_PPG;
                msg.obj = data;
                mHandler.sendMessage(msg);
            }
        }
        @Override
        public void onMtuChanged(BluetoothGatt gatt, int mtu, int status) {
            super.onMtuChanged(gatt, mtu, status);
            if (status == BluetoothGatt.GATT_SUCCESS) {
                Log.d(TAG, "MTU changed to: " + mtu);
            }
        }
    };

    @SuppressLint("MissingPermission")
    private void enableNotifications(BluetoothGatt gatt, BluetoothGattCharacteristic characteristic) {
        gatt.setCharacteristicNotification(characteristic, true);
        BluetoothGattDescriptor descriptor = characteristic.getDescriptor(CLIENT_CHARACTERISTIC_CONFIG_UUID);
        if (descriptor != null) {
            descriptor.setValue(BluetoothGattDescriptor.ENABLE_NOTIFICATION_VALUE);
            gatt.writeDescriptor(descriptor);
        }
    }
    private static final int HANDLE_MESSAGE_ECG = 1;
    private static final int HANDLE_MESSAGE_ACC = 2;
    private static final int HANDLE_MESSAGE_BREATHE = 3;
    private static final int HANDLE_MESSAGE_PPG = 4;
    private static final int HANDLE_MESSAGE_HR = 5;
    private static final int HANDLE_MESSAGE_SO2 = 6;
    private static final int HANDLE_MESSAGE_BATTERY = 7;
    private final Handler mHandler = new Handler(new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case HANDLE_MESSAGE_ECG:
                {
                    byte[] data = (byte[])msg.obj;
                    float[] cECG_buf = new float[32];
                    float[] raw_cECG_buf = new float[32];
                    for(int i = 0; i<(data.length/4); i++) {
                        float fECG = DataUtils.bytes2Float(Arrays.copyOfRange(data, i*4,(i+1)*4));
                        cECG_buf[i] = fECG;
                        PlotWave.getInstance().ecgEntries.add(new Entry(PlotWave.getInstance().ecgEntries_index++, cECG_buf[i]));

//                        algorithm.getInstance().ecgData[algorithm.getInstance().index++] = cECG_buf[i];
//                        if (algorithm.getInstance().index >= 256*2){
//                            algorithm.getInstance().index = 0;
//                            int heartRate = (int) algorithm.getInstance().calculateHeartRate(algorithm.getInstance().ecgData,2);
//                            //List<Integer> RRI = algorithm1.findPeaks(algorithm.getInstance().ecgData,2*256, algorithm1.minPeakDistance, algorithm1.minPeakHeight);
//                            //int heartRate = algorithm1.hr;
//                            if(heartRate == 0) {
//                                HomeInterfaceInstant.getInstance().onUpdateHrRequested("--");
//                            }else {
//                                heartRate = HeartRateCalibrator.getInstance().calibrate(heartRate);
//                                HomeInterfaceInstant.getInstance().onUpdateHrRequested(heartRate + "");
//                            }
//                        }
//                        //计算呼吸
//                        RespiratoryRateCalculator.getInstance().addData(cECG_buf[i], PlotWave.getInstance().ecgEntries_index-1);
//                        HomeInterfaceInstant.getInstance().onUpdateTempCRequested(((int)RespiratoryRateCalculator.getInstance().resp+""));
                    }
                    PlotWave.getInstance().updateChart(HomeInterfaceInstant.getInstance().get_ChartECG(), PlotWave.getInstance().ecgEntries, "ECG", Color.RED,1000,32);
                    if(csvDataLogger_ecg != null){
                        csvDataLogger_ecg.addData(cECG_buf);
                    }
                }break;
                case HANDLE_MESSAGE_ACC:
                {
                    String s = (String) msg.obj;
                    /* 1:获取accX */
                    int index_start = 5;
                    int index_end = s.indexOf("accy",1);
                    float accX = Float.parseFloat(s.substring(index_start, index_end-1));
                    /* 2:获取accY */
                    index_start = index_end+5;
                    index_end = s.indexOf("accz",index_end+1);
                    float accY = Float.parseFloat(s.substring(index_start, index_end-1));
                    /* 3:获取accZ */
                    index_start = index_end+5;
                    index_end = s.indexOf("tempc",index_end+1);
                    float accZ = Float.parseFloat(s.substring(index_start, index_end-1));
                    /* 4:获取tempC */
                    index_start = index_end+6;
                    index_end = s.length();
                    float tempC = Float.parseFloat(s.substring(index_start, index_end));
                    // 发送数据
                    PlotWave.getInstance().accXEntries.add(new Entry(PlotWave.getInstance().accEntries_index, accX));
                    PlotWave.getInstance().accYEntries.add(new Entry(PlotWave.getInstance().accEntries_index, accY));
                    PlotWave.getInstance().accZEntries.add(new Entry(PlotWave.getInstance().accEntries_index, accZ));
                    PlotWave.getInstance().accEntries_index++;
                    PlotWave.getInstance().updateMultiLineChart(HomeInterfaceInstant.getInstance().get_chartACC(),
                            new List[]{PlotWave.getInstance().accXEntries, PlotWave.getInstance().accYEntries, PlotWave.getInstance().accZEntries},
                            new String[]{"X轴", "Y轴", "Z轴"},
                            new int[]{Color.RED, Color.GREEN, Color.BLUE},100,1);
                    if(csvDataLogger_acc != null){
                        csvDataLogger_acc.addData(new float[]{accX}, new float[]{accY}, new float[]{accZ});
                    }
                }break;
                case HANDLE_MESSAGE_BREATHE: {
                    // Resp
                    int RESPIRATORY_RATE_WINDOW_SIZE = 38; // 呼吸率窗口大小
                    double[] breathe_ch0 = new double[RESPIRATORY_RATE_WINDOW_SIZE];
                    float[] breathe_raw = new float[RESPIRATORY_RATE_WINDOW_SIZE];// 存储原始数据
                    byte[] data = (byte[])msg.obj;
                    for(int i = 0; i<(data.length/4); i++) {
                        float raw_data = DataUtils.bytes2Float(Arrays.copyOfRange(data, i*4,(i+1)*4));
                        breathe_raw[i] = raw_data;
                        breathe_ch0[i] = raw_data;

                        double sampleData = breatheData.breatheData[breatheData.index++];
                        if(breatheData.index >= breatheData.breatheData.length)
                        {
                            breatheData.index = 0;
                        }

                        //breathe_ch0[i] = sampleData;
                        filter.getInstance().addResp(breathe_ch0[i]);
                        filter.getInstance().RespWindowIndex++;
                    }
                    if(filter.getInstance().RespWindowIndex >= filter.getInstance().filtfilt_breathe_len && filter.getInstance().isRespWindowFull()){
                        filter.getInstance().RespWindowIndex = 0;
                        double[] value = filter.getInstance().filtfilt_breathe(filter.getInstance().getRespWindow());
                        for (int i = 0; i < filter.getInstance().filtfilt_breathe_len; i++) {
                            // 更新呼吸图表
                            PlotWave.getInstance().breathEntriesCH0.add(new Entry(PlotWave.getInstance().breatheEntries_index++, (float)value[i]));
                        }
                        PlotWave.getInstance().updateChart1(HomeInterfaceInstant.getInstance().get_chartBreath(), PlotWave.getInstance().breathEntriesCH0, "RESP", Color.parseColor("#36D1DC"),
                                filter.getInstance().filtfilt_breathe_len, filter.getInstance().filtfilt_breathe_len,11000,120,-120);
                        if(csvDataLogger_breathe_filtered != null){
                            csvDataLogger_breathe_filtered.addData(DataUtils.doubleArrayToFloatArray(value));
                        }
                    }
                    if (csvDataLogger_breathe != null){
                        csvDataLogger_breathe.addData(breathe_raw);
                    }
                }break;
                case HANDLE_MESSAGE_PPG: {
                    // PPG
                    int PPG_WINDOW_SIZE = 25;
                    float[] raw_red = new float[PPG_WINDOW_SIZE];// 存储原始RED数据
                    float[] raw_ir = new float[PPG_WINDOW_SIZE];// 存储原始IR数据
                    byte[] data = (byte[])msg.obj;
                    for(int i = 0; i<(data.length/8); i++) {
                        long LRed = DataUtils.bytesToUnsignedInt(Arrays.copyOfRange(data, i*8,i*8+4));
                        raw_red[i] = LRed;// 存储原始数据
                        double smoothRedValue = MovingAverageSmoother.getInstance().smooth(LRed);

                        long LIr = DataUtils.bytesToUnsignedInt(Arrays.copyOfRange(data, i*8+4,i*8+8));
                        raw_ir[i] = LIr;
                        double smoothIrValue = MovingAverageSmoother.getInstance1().smooth(LIr);

                        double sampleData = ppgData.data[ppgData.index++] * 1000.0F;
                        if(ppgData.index >= ppgData.data.length)
                        {
                            ppgData.index = 0;
                        }

                        filter.getInstance().add(smoothIrValue);
                        filter.getInstance().windowIndex++;
                    }
                    if(filter.getInstance().windowIndex >= 400 && filter.getInstance().isWindowFull()){
                        filter.getInstance().windowIndex = 0;
                        double[] value = filter.getInstance().filtfilt_ppg(filter.getInstance().getWindow());
                        for (int i = 0; i < 400; i++) {
                            PlotWave.getInstance().ppgEntriesRED.add(new Entry(PlotWave.getInstance().ppgEntries_index++, (float)value[i]));
                        }
                        PlotWave.getInstance().updateChart1(HomeInterfaceInstant.getInstance().get_chartPPG(), PlotWave.getInstance().ppgEntriesRED,"PPG", Color.parseColor("#E100FF"),
                                400, 400, 3600,150,-150);
                        if (csvDataLogger_ppg_filtered != null){
                            csvDataLogger_ppg_filtered.addData(DataUtils.doubleArrayToFloatArray(value));
                        }
                    }
                    // 记录的是原始数据
                    if (csvDataLogger_ppg != null){
                        csvDataLogger_ppg.addData(raw_red, raw_ir);
                    }

                }break;
                case HANDLE_MESSAGE_HR: {
                    String s = (String) msg.obj;
                    Log.d("lzy", "HR data: " + s);
                    /* 1:获取hr */
                    int index_start = 3;
                    int index_end = s.indexOf("resp",1);
                    int hr = Integer.parseInt(s.substring(index_start, index_end-1));
                    HomeInterfaceInstant.getInstance().onUpdateHrRequested(hr + "");
                    /* 2:获取平均rri */
                    index_start = index_end+5;
                    index_end = s.length();
                    int resp = Integer.parseInt(s.substring(index_start, index_end));
                    HomeInterfaceInstant.getInstance().onUpdateTempCRequested(resp + "");
                }break;
                case HANDLE_MESSAGE_SO2:{
                    String s = (String) msg.obj;
                    int index_start = 4;
                    int index_end = s.length();
                    int so2 = Integer.parseInt(s.substring(index_start, index_end));
                    if(so2==0) {
                        HomeInterfaceInstant.getInstance().onUpdateStepsRequested("--");
                    }
                    else {
                        HomeInterfaceInstant.getInstance().onUpdateStepsRequested(so2 + "");
                    }
                }break;
                case HANDLE_MESSAGE_BATTERY: {
                    String s = (String) msg.obj;
                    int index_start = 8;
                    int index_end = s.length();
                    int battery = Integer.parseInt(s.substring(index_start, index_end));
                    MainActivity.setBatteryPercent(battery);
                }break;
            }
            return true;
        }
    });
}
